package com.example.httpdemo.demos.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.httpdemo.demos.service.IOkHttpService;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Objects;

/**
 * 〈〉
 *
 * @author hero
 * @create 2024/5/17
 * @since 1.0.0
 */
@Service
public class OkHttpServiceImpl implements IOkHttpService {

    @Autowired
    OkHttpClient okHttpClient;

    @Override
    public String testGet() throws Exception {
        String getUrl="http://localhost:9510/testGet?id=100";
        String strResult="";
        Request req=new Request.Builder().url(getUrl).build();
        try(Response re = okHttpClient.newCall(req).execute()){
            if (re.isSuccessful()){
                assert re.body() != null;
                strResult= re.body().string();
            } else {
                strResult="请求失败！！！";
            }
        }
        return strResult;
    }

    @Override
    public String testPost() throws Exception {
        String strResult = "";
        String strJson="{\n" +
                "  \"fid\": \"fid_9e8c29796e21\",\n" +
                "  \"fname\": \"fname_a5970f5e02a6\",\n" +
                "  \"forder\": 0,\n" +
                "  \"fatherId\": \"fatherId_7418a948a8f7\",\n" +
                "  \"fatherName\": \"fatherName_77b7379ab274\"\n" +
                "}";
        RequestBody requestBody = RequestBody.create(strJson, MediaType.get("application/json"));
        Request req=new Request.Builder()
                .url("http://localhost:9510/testPost")
                .post(requestBody)
                .build();
        try(Response re = okHttpClient.newCall(req).execute()) {
            if (re.isSuccessful()){
                assert re.body() != null;
                strResult= re.body().string();
            } else {
                strResult="请求失败！！！";
            }
        }
        return strResult;
    }
}





